package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.constant.enu.RegisterStatus;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.Userinfo;
import com.quickcancellation.crm.pojo.vo.RoleVo;
import com.quickcancellation.crm.service.IRoleService;
import com.quickcancellation.crm.service.IUserinfoService;
import com.quickcancellation.crm.utils.JSONUtils;
import com.quickcancellation.crm.utils.MD5Util;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-02-22
 */
@RestController
@RequestMapping("/userinfo")
@CrossOrigin
@Api(tags = "用户管理")
@SaCheckLogin
@SaCheckRole("userInfo")
public class UserinfoController {


    @Resource
    private IUserinfoService userinfoService;

    @Resource
    private IRoleService roleService;

    @Resource
    HttpServletRequest request;

    /**
     * 查询用户列表
     *
     * @param params
     * @return
     */
    @ApiOperation("用户列表查询")
    @PostMapping("/list")
    @LogAspect
    public ResponseDto userList(@RequestBody PageParamsDto<Userinfo> params) {

        // 防止空传
        if (null == params.getParams()) {
            params.setParams(new Userinfo());
        }

        IPage<Userinfo> iPage = userinfoService.selectUserInfoList(params);

        return ResponseUtil.success(iPage.getTotal(), null == iPage.getRecords() ? null : iPage.getRecords());

    }

    @ApiOperation("添加用户")
    @LogAspect
    @PostMapping("save")
    public ResponseDto saveUserInfo(@RequestBody Map<String, Object> params) {

        Userinfo userinfo = JSONUtils.getEntity(MapUtils.getObject(params, "userinfo"), Userinfo.class);
        List<Object> roleList = JSONUtils.getEntity(MapUtils.getObject(params, "roleList"), List.class);

        // 获取当前用户操作
        Userinfo currentUser = userinfoService.getUserInfoByRequest(request);
        String currentUserNumber = currentUser.getUsernumber();

        // TODO : FIX 自增主键过长
        // 校验用户信息是否合法
        RegisterStatus status = userinfoService.checkUserInfo(userinfo);
        // 格式合法
        if (status.equals(RegisterStatus.LEGAL)) {
            // 设置密码，默认密码为手机号
            userinfo.setPassword(MD5Util.getMD5(userinfo.getPassword()));

            boolean result = userinfoService.save(userinfo);

            boolean addRuleResult = roleService.addOrDelUserRole(userinfo.getUsernumber(), roleList, currentUserNumber);

            return result && addRuleResult ? ResponseUtil.success() : ResponseUtil.fail("-501", "添加失败");
        }

        return ResponseUtil.fail(status.getCode().toString(), status.getDescription());

    }


    @ApiOperation("修改用户信息")
    @LogAspect
    @PostMapping("update")
    public ResponseDto updateUserInfo(@RequestBody Map<String, Object> params) {
        Userinfo userinfo = JSONUtils.getEntity(MapUtils.getObject(params, "userinfo"), Userinfo.class);
        List<Object> roleList = JSONUtils.getEntity(MapUtils.getObject(params, "roleList"), List.class);

        // 获取当前用户操作
        Userinfo currentUser = userinfoService.getUserInfoByRequest(request);
        String currentUserNumber = currentUser.getUsernumber();

        String usernumber = userinfo.getUsernumber();

        // 将不可以编辑的信息去除
        userinfo.setMobile(null);
        userinfo.setPassword(null);
        userinfo.setUsername(null);
        userinfo.setUsernumber(null);

        if (null == userinfo.getId()) {
            return ResponseUtil.fail("-506", "缺少id");
        }

        boolean result = userinfoService.updateById(userinfo);

        boolean addRuleResult = roleService.addOrDelUserRole(usernumber, roleList, currentUserNumber);

        return result && addRuleResult ? ResponseUtil.success() : ResponseUtil.fail("-501", "更新失败");
    }

    /**
     * 修改密码
     *
     * @param params 入参
     * @return 是否修改成功
     */
    @ApiOperation("修改密码")
    @LogAspect
    @PostMapping("updatePassword")
    public ResponseDto updatePassword(@RequestBody Map<String, String> params) {

        String userId = MapUtils.getString(params, "id");
        String oldPassword = MapUtils.getString(params, "oldPassword");
        String newPassword = MapUtils.getString(params, "newPassword");

        if (!StringUtils.hasLength(userId)) {
            return ResponseUtil.fail("-506", "[userId]为空");
        }
        if (!StringUtils.hasLength(oldPassword)) {
            return ResponseUtil.fail("-507", "[旧密码]为空");
        }
        if (!StringUtils.hasLength(newPassword)) {
            return ResponseUtil.fail("-508", "[新密码]为空");
        }

        boolean checkPassword = userinfoService.checkUserPassword(userId, oldPassword);

        if (!checkPassword) {
            return ResponseUtil.fail("-509", "原密码错误");
        }

        if (newPassword.length() <= 6) {
            return ResponseUtil.fail("-510", "密码长度至少为6位");
        }


        if (oldPassword.equals(newPassword)) {
            return ResponseUtil.fail("-506", "[新密码]和[旧密码]相同");
        }

        boolean result = userinfoService.updatePassword(userId, newPassword);

        return result ? ResponseUtil.success() : ResponseUtil.fail("-511", "密码修改失败");
    }

    @ApiOperation("修改密码")
    @LogAspect
    @PostMapping("delete")
    public ResponseDto deleteUserInfo(@RequestBody Map<String, String> params) {

        String userId = MapUtils.getString(params, "id");

        boolean result = userinfoService.removeById(userId);

        return result ? ResponseUtil.success() : ResponseUtil.fail("-511", "删除失败");
    }

    @ApiOperation("查询用户权限")
    @LogAspect
    @PostMapping("getRoleList")
    public ResponseDto getRoleList(@RequestBody Map<String, String> params) {

        String usernumber = MapUtils.getString(params, "usernumber");


        List<RoleVo> roleList = roleService.getRoleVoByUsernumber(usernumber);

        return ResponseUtil.success(roleList.size(), roleList);

    }


}
